package com.matu.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.matu.domain.Personnel;
import com.matu.util.DB;


@Controller
public class ConnexionController {

	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	@RequestMapping(value = "/connexion", method = RequestMethod.POST)
	public String connexion(Locale locale, Model model, HttpServletRequest request,HttpServletResponse response) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
		
		/*
		 * Si il y a un paramètre déconnexion, on invalide 
		 * la session.
		 */
		String deconnexion = (String) request.getParameter("deconnexion");
		String page = request.getHeader("Referer");
		
		if (deconnexion == null){

			String id = (String) request.getParameter("id");
			String password = (String) request.getParameter("password");
			
			/*
			 * Vérification de connexion
			 */
			DB db = new DB();	
			
			ArrayList<Personnel> listP = db.getClassOfObjectsInDB(Personnel.class);
			boolean connected = false;
			String _id = "";
			for (Personnel p : listP){
				
				if (id.equals(p.getNom()) &&  password.equals(p.getPassword()) ){
					connected = true;
					_id = p.getId();
				}
			}
			
			
			/*
			 * Si la connexion réussie, on crée une session
			 * sinon on l'invalide
			 */
			if (connected){
				request.getSession().setAttribute("user", id);
				request.getSession().setAttribute("userid", _id);
				
				
				try {
					response.sendRedirect(page);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}else
			{
				request.getSession().invalidate();
			}
		
		}
		else
		{
			request.getSession().setAttribute("user", null);
			request.getSession().setAttribute("userid",null);

			try {
				response.sendRedirect(page);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		

		return "connexion";
	}
}
